# ai-daily/webhook_server.py

from fastapi import FastAPI, Request
import subprocess
import os
import uvicorn

app = FastAPI()

# 可选：设置一个 token 增加安全性
WEBHOOK_SECRET_TOKEN = "mydaily_guagua_0327"  # 和 Gitee 设置的一致

@app.post("/webhook")
async def handle_webhook(request: Request):
    # 可选：验证请求来源是否来自 Gitee
    headers = request.headers
    token = headers.get("X-Gitee-Token")
    if token != WEBHOOK_SECRET_TOKEN:
        print("Invalid token:", token)
        return {"status": "error", "message": "Invalid token"}, 403

    print("Webhook received. Pulling latest code...")

    # 更新后端代码
    backend_path = os.path.join(os.path.dirname(__file__), "backend")
    subprocess.run(["git", "pull", "origin", "main"], cwd=backend_path)

    # 更新前端代码（如果 frontend 也是一个 git 仓库）
    frontend_path = os.path.join(os.path.dirname(__file__), "frontend")
    if os.path.exists(frontend_path):
        subprocess.run(["git", "pull", "origin", "main"], cwd=frontend_path)

    print("Code updated. Restarting service...")
    # 根据你实际使用的进程管理工具修改下面这行
    subprocess.run(["systemctl", "restart", "gunicorn"])  # 或 pm2 restart backend 等

    return {"status": "success"}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)